import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { Button, Divider, Dropdown, Menu, message, Modal, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryShop, batchRemoveShop, getScrollInfo, deleteManyImg, uploadManyImg,preContractQRCode } from './service';
import { HasPermission } from '@/components/AuthComponent/HasPermission';
import styles from './style.less';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
const baseUrl = 'http://mmm.supercube.vip/'
/**
 *  批量删除
 * @param selectedRows
 */
const handleRemove = async selectedRows => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  let ids = selectedRows.map(row => row.id);
  try {
    await batchRemoveShop(ids);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
/**
 * 新增
 * @param {*} async 
 */
const goToSave = async => {
  history.push(`/shop/center/save`);
};

/**
 * 编辑
 * @param {*} async 
 */
const goToEdit = async record => {
  history.push(`/shop/center/update/${record.id}`);
};
/**
 * 进入场地
 * @param {*} record 
 */
 const goToSite = async record => {
  history.push(`/site/center/${record.id}`);
};

const List = () => {
  const actionRef = useRef();
  const [currentVenue, setCurrentVenue] = useState({});
  const [visible, setVisible] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const columns = [
    {
      title: '场馆名称',
      dataIndex: 'name',
    },
    {
      title: '电话',
      dataIndex: 'telephone'
    },
    {
      title: '省',
      dataIndex: 'provincialName',
      hideInSearch: true
    },
    {
      title: '市',
      dataIndex: 'cityName',
      hideInSearch: true
    },
    {
      title: '区',
      dataIndex: 'districtName',
      hideInSearch: true
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      hideInSearch: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        1: {
          text: '正常',
          status: 'Success',
        },
        2: {
          text: '暂停',
          status: 'Error',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`shop:update`]} type="link" onClick={() => goToEdit(record)}>编辑</AuthButton>
          <AuthDivider auth={['shop:fullscreen', `shop:update`]} type="vertical"></AuthDivider>
          <AuthButton auth={[`shop:site`]} type="link"  onClick={() => goToSite(record)}>场地</AuthButton>
         <AuthDivider auth={['shop:site',`shop:update`]} type="vertical"></AuthDivider>
          <AuthButton auth={[`shop:fullscreen`]} type="link" onClick={() => showFullScreen(record)}>场馆大屏</AuthButton>
        </>
      ),
    },
  ];
  const showFullScreen = async (record) => {
    setVisible(true);
    setCurrentVenue(record)
    const scrollInfo = await getScrollInfo({ venueId: record.id });
    if (scrollInfo) {
      setImageUrl(`${baseUrl}${scrollInfo?.qrcode}`);
      setImgList(scrollInfo?.imgList ?? [])
      if (scrollInfo?.imgList) {
        let imgList = scrollInfo?.imgList.map((item) => {
          let name = item.pictureUrl?.substr(item.pictureUrl?.lastIndexOf('/') + 1);
          return {
            uid: item.id,
            name: name,
            status: 'done',
            url: `${baseUrl}${item.pictureUrl}`
          }
        })
        setFileList(imgList)
      }
    }

  }
  const handleOk = () => {

  }
  const handleChange1 = async ({ file, fileList: newFileList }) => {
    setFileList(newFileList);
  }
  const onRemove1 = async(file)=>{
    const delOne = imgList.find(item => item.id === file.uid);
    await deleteManyImg({ ...delOne });
  }
  const handleChange2 = () => {

  }
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('请上传jpeg/png图片');
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      message.error('图片不可以大于10M');
    }
    return isJpgOrPng && isLt2M;
  };
  const uploadButton1 = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <AuthButton auth={[`shop:add`]} type="primary" icon={<PlusOutlined />} onClick={() => goToSave()}>新增</AuthButton>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      await handleRemove(selectedRows);
                      action.reload();
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                </Menu>
              }
            >
              <AuthButton auth={[`shop:batch:delete`]}>批量操作<DownOutlined /></AuthButton>
            </Dropdown>
          ),
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项
          </div>
        )}
        request={params => {
          let _params = {
            pageNum: params.current,
            ...params,
          }
          delete _params.current
          return queryShop(_params)
        }}
        postData={result => result.list}
        columns={columns}
        rowSelection={{}}
      />
      <Modal title='场馆大屏' visible={visible} onOk={handleOk} onCancel={() => {
        setVisible(false)
        setCurrentVenue({})
      }} footer={<Button onClick={() => {
        setVisible(false)
        setCurrentVenue({})
      }}>取消</Button>}>
        <p>轮播图片</p>
        <Upload
          name='file'
          listType="picture-card"
          fileList={fileList}
          onChange={handleChange1}
          onRemove={onRemove1}
          beforeUpload={beforeUpload}
          customRequest={async ({file,filename}) => {
            const formData = new FormData();
            formData.append(filename, file);
            formData.append('venueId',currentVenue.id)
            const result = await uploadManyImg(formData)
            if(result.code ===0){
              let _fileList = [...fileList];
              _fileList.splice(fileList.length-1)
              let name = result?.data.pictureUrl?.substr(result?.data.pictureUrl?.lastIndexOf('/') + 1);
              setFileList([..._fileList,{
                name,
                uid:result?.data.id,
                status: "done",
                url:`${baseUrl}${result?.data.pictureUrl}`
              }]);
            }
            return {
              abort() {
                console.log('upload progress is aborted.');
              },
            };
          }}
        >
          {fileList.length >= 8 ? null : uploadButton1}
        </Upload>
        <p>二维码</p>
        <div className={styles.codeWrap}>
          <div className={styles.codeImageWrap}>
            <img src={imageUrl} alt="avatar" className={styles.codeImage} />
          </div>
          <Button className={styles.btn} onClick={async()=>{
            const formData = new FormData();
            formData.append('venueId',currentVenue.id)
            const result = await preContractQRCode(formData)
            if(result.code ===0){
              setImageUrl(`${baseUrl}${result.message}`);
            }
          }}>生成二维码</Button>
        </div>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default List;
